package org.dbstar.scheduler.serializer;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;

import org.apache.commons.io.IOUtils;

/**
 * Serializer that writes an object to an output stream using Java Serialization.
 * 
 * @author 代波
 * @since 1.0.0
 * @version 1.0.0
 * @date 2012-4-7
 */
public class DefaultSerializer<T extends Serializable> implements Serializer<T> {
	/**
	 * Writes the source object to an output stream using Java Serialization. The source object must implement
	 * {@link Serializable}.
	 */
	@Override
	public void serialize(T object, OutputStream outputStream, boolean close) throws IOException {
		try {
			ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
			objectOutputStream.writeObject(object);
			objectOutputStream.flush();
		} finally {
			if (close) {
				IOUtils.closeQuietly(outputStream);
			}
		}
	}

	/**
	 * Reads the input stream and deserializes into an object.
	 */
	@SuppressWarnings("unchecked")
	@Override
	public T deserialize(InputStream inputStream, boolean close) throws IOException {
		try {
			ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
			try {
				return (T) objectInputStream.readObject();
			} catch (ClassNotFoundException ex) {
				throw new IOException("Failed to deserialize object type", ex);
			}
		} finally {
			if (close) {
				IOUtils.closeQuietly(inputStream);
			}
		}
	}
}
